//全局实际产量
var SJCL_QTY = 0 ;
var userId = "";  //当前登录用户id
var userName = ""; //当前登录用户姓名
var dlName = "";

layui.use(['element', 'layer'],

function() {
});

//左上角箭头点击
layui.use(['jquery', 'element'], function() {
    var $ = layui.jquery;
    $('#h3').on('click', function() {
        addAllPerson();
        suggestBM();
    });
});


function onlineCollapse(){
    var list = document.getElementById('onlineStaffInfo');
    if (list.style.display === "none"){
        list.style.display = "block";
    } else {
        list.style.display = "none";
    }
}

function initWxConfig(){
    var wxAppId = "";
    var timestamp = "";
    var nonce_str = "";
    var signature = "";
    var url = globalVar.URL_SHARE;
    var data = {
    	urlSigna: encodeURIComponent(window.location.href)
    };
    jQuery.getJSON(url, data,
    function(res) {
    	wxAppId = res.obj.appId;
    	timestamp = res.obj.timesTamp;
    	nonce_str = res.obj.noncestr;
    	signature = res.obj.signature;
    	wx.config({
    		debug: false,
    		// 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，                                                            仅在pc端时才会打印。
    		appId: wxAppId,
    		// 必填，公众号的唯一标识
    		timestamp: timestamp,
    		// 必填，生成签名的时间戳
    		nonceStr: nonce_str,
    		// 必填，生成签名的随机串
    		signature: signature,
    		// 必填，签名，见附录1
    		jsApiList: ['scanQRCode']
    	});
    });
}

//页面初始化
$(document).ready(function() {
    document.getElementById('zhezhao').style.display = "none";
    document.getElementById('onlineStaffInfo').style.display = "none";
    userId = window.location.search.substr(1).split("&")[0].split("=")[1];
    userName = window.location.search.substr(1).split("&")[1].split("=")[1];
    //测试数据
    // userId = "227103";
    // userName = "郑竹成";
    dlName = decodeURI(userName);
        
    addAllPerson();
    suggestBM();   
    initWxConfig();
});

//顶端列表显示在线员工
function showOnlineEMP(res){
    if (!res.data) {
        return 
    }
    //查询所有员工
    var data = res.data;
    for (var i = 0; i < data.length; i++) {
    	var trObj = document.createElement("tr");
    	var j = i+1;
    	var id = data[i].ID;
    	var name = data[i].NAME;
    	var mo = data[i].MO;
    	var sec = data[i].SEC;
    	if (mo == null) {
    		mo = "";
    	}
    	if (sec == null) {
    		sec = "";
    	}
    	var state = data[i].STATE;
    	if (state == 0) {
    		state = "上线";
    		trObj.innerHTML ="<td style='width: 5%;'>"+j+ "</td><td style='width: 22%;'>" + id + "</td><td style='width: 17%;'>" + name + "</td><td style='width: 37%;'>" + mo + "</td><td style='width: 19%;'>"+ sec +"</td>";
    		//trObj.style.backgroundColor='#00d466';
    	} else {
    		state = '下线';
    		trObj.innerHTML = "<td>" + id + "</td><td>" + name + "</td><td>" + mo + "</td><td></td>";
    	}
    	document.getElementById("allPerson").appendChild(trObj);
    }
    document.getElementById("h3").innerHTML = "";
    var text = document.createElement("i");
    text.innerHTML = "在线员工  <span class='layui-badge-rim'>"+data.length+"人</span>&nbsp;&nbsp;&nbsp;&nbsp;"+"操作人 : "+dlName;
    document.getElementById("h3").appendChild(text);
    var element = layui.element;
    element.render();
}

//查找所有员工
function addAllPerson() {
    var tablebody = document.getElementById('allPerson');
    tablebody.innerHTML = "";
    
    http_get_sync(
        globalVar.URL_SEARCHPERSONALL,
        {},
        function(res){ 
            showOnlineEMP(res) 
        },
        function(err){
            console.log(err)
            layer.msg("服务端异常,请联系开发人员查看");
        }
    );
}

//填充部门下拉列表
function suggestBM() {
    var select = $("#bmList");
    http_get_sync(
        globalVar.URL_SEARCHBM,
        {},
        function(res) {
            if (res.status){
                $("#bmList").html("");
                select.append("<option>全部</option>");
                var data = res.data;
                for (var i = 0; i < data.length; i++) {
                    select.append('<option value=' + data[i].BU_ID + '>' +data[i].BU_ID+ '</option>');
                }
            }
        },
        function(err){
            console.log(err)
            layer.msg("服务端异常,请联系开发人员查看");}
    );
}

//部门选择		
function changeBM(id){
    var aa = document.getElementById(id);
    var i = aa.selectedIndex;
    var bmid = aa.options[i].value;
    document.getElementById("bmList").value =bmid;
    addAllPersonByBM(bmid);
}

//按部门查找所有员工
function addAllPersonByBM(bmid) {
    var tablebody = document.getElementById('allPerson');
    tablebody.innerHTML = "";
    
    http_get_sync(
        globalVar.URL_SEARCHPERSONALLBYBM,
        {
            bmid:bmid,
        },
        function(res){ 
            showOnlineEMP(res) 
        },
        function(err){
            console.log(err)
            layer.msg("服务端异常,请联系开发人员查看");}
    );
}


//班别选择
function changeBB(id){
    var aa = document.getElementById(id);
    var i = aa.selectedIndex;
    var value = aa.options[i].value;
    document.getElementById(id).value =value;
}

//模糊匹配 选择工单
function changeF(id){
    var aa = document.getElementById(id);
    var i = aa.selectedIndex;
    var value = aa.options[i].value;
    if (id == "gdList"){
        document.getElementById("gdh").value =value;
    } else if  (id = "gdList2") {
        document.getElementById("gdh2").value =value;
    } 
}

//填充工单信息
function suggestGD(id) {
    if (id == "gdh") {
        $("#scxm").val(""); //生产线码
        $("#cpbm").val(""); //产品编码
        $("#gdsl").val(""); //工单数量
        $("#cpms").val(""); //产品描述
        $("#rptid").val("");
        
        var tabT = document.getElementById('tabT');
        tabT.innerHTML = "";
        
        $("#gdList").html("");
        $("#gdList").append("<option>-----请选择工单-----</option>"); 
        $("#gydList").html("");
        $("#gydList").append("<option>请选择工艺段</option>"); 
    } else if (id == "gdh2") {
        $("#scxm2").val(""); //生产线码
        $("#cpbm2").val(""); //产品编码
        $("#gdsl2").val(""); //工单数量
        $("#cpms2").val(""); //产品描述
        $("#gdList2").html("");
        $("#gdList2").append("<option>---请选择目标工单---</option>"); 
    }
    
    if (id == "gdh"){
        var gdh = $("#gdh").val();
        var select = $("#gdList");
    } else if (id == "gdh2") {
        var gdh = $("#gdh2").val();
        var select = $("#gdList2");
    }
    
    if (gdh == ''|| gdh.length<9) {
        select.html("");
        return;
    }
    
    http_get_sync(
        globalVar.URL_SEARCHGDLIKE,
        {
            gdh: gdh,
        },
        function(res){ 
            if (id == "gdh"){
                $("#gdList").html("");
            } else if (id == "gdh2") {
                $("#gdList2").html("");
            }
            select.append("<option>-----请选择工单-----</option>"); 
            var data = res.data;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value=' + data[i].MO + '>' +data[i].MO+ '</option>');
            }},
        function(err){
            console.log(err)
            layer.msg("服务端异常,请联系开发人员查看");
        })
}; 
        
//填充工艺段下拉列表				
function suggestGYD(id) {
    if (id == "search1") {
        var gdh = $("#gdh").val();
        var select = $("#gydList");
    } else if (id == "search2"){
        var gdh = $("#gdh2").val();
        var select = $("#gydList2");
    }
        
    http_get_sync(
        globalVar.URL_SEARCHGYD,
        {
            gdh: gdh,
        },
        function(res){
            if (id == "search1") {
                $("#gydList").html("");
            } else if (id == "search2"){
                $("#gydList2").html("");
            }
            select.append("<option>请选择工艺段</option>");
            var data = res.data;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value=' + data[i].PROD_SEC + '>' +data[i].PROD_SEC+ '</option>');
            }
        },
        function(err){
            console.log(err)
            layer.msg("服务端异常,请联系开发人员查看");
        }
        );
}; 

//重置按钮
function resetClick(id){
    if (id == "reset1") { //重置按钮1
        $("#gdh").val(""); //工单号
        $("#scxm").val(""); //生产线码
        $("#cpbm").val(""); //产品编码
        $("#gdsl").val(""); //工单数量
        $("#cpms").val(""); //产品描述
        $("#rptid").val("");
        var tabT = document.getElementById('tabT');
        tabT.innerHTML = "";
        
        $("#gdList").html("");
        $("#gdList").append("<option>-----请选择工单-----</option>"); 
        $("#gydList").html("");
        $("#gydList").append("<option>请选择工艺段</option>"); 
        $("#gdh").focus();
    } else if (id == "reset2") { //重置按钮2
        $("#gdh2").val(""); //工单号
        $("#scxm2").val(""); //生产线码
        $("#cpbm2").val(""); //产品编码
        $("#gdsl2").val(""); //工单数量
        $("#cpms2").val(""); //产品描述
        $("#gdList2").html("");
        $("#gdList2").append("<option>---请选择目标工单---</option>"); 
        $("#gydList2").html("");
        $("#gydList2").append("<option>请选择工艺段</option>"); 
        $("#gdh2").focus();
    }
}


function hideClick(id){
    if (id == "gdxxyc1") {
        var div = document.getElementById('gdxx1');
    } else if (id == "gdxxyc2"){
        var div = document.getElementById('gdxx2');
    }
    if (div.style.display == "none"){
        div.style.display = "block";
        document.getElementById(id).innerHTML ="收起";
    } else {
        div.style.display = "none";
        document.getElementById(id).innerHTML ="展开";
    }
    
}

//查询工单信息（搜索按钮）
function searchClick(id){    
    if (id == "search1") {
        var gdh = $('#gdh');
        var scxm = $("#scxm");
        var cpbm = $("#cpbm");
        var gdsl = $("#gdsl");
        var cpms = $("#cpms");
    } else if (id == "search2"){
        var gdh = $('#gdh2');
        var scxm = $("#scxm2");
        var cpbm = $("#cpbm2");
        var gdsl = $("#gdsl2");
        var cpms = $("#cpms2");
    }
    
    mo = gdh.val();

    if (mo == '') {
        layer.msg("请先输入工单号");
        gdh.focus();
        return;
    }
    
    http_get_sync(
        globalVar.URL_SEARCHGD,
        {
            gdh: mo
        },
        function(res){
            if (res.status) {
                scxm.val(res.data.PL_ID); //生产线码
                cpbm.val(res.data.PROD_ID); //产品编码
                gdsl.val(res.data.P_QTY); //工单数量
                cpms.val(res.data.MTRL_DESC); //产品描述
                suggestGYD(id);
            } else {
                layer.msg(res.message);
                gdh.focus();
            }
        },
        function(err){
            console.log(err)
            layer.msg("服务端异常,请联系开发人员查看");
        }
    );
}

//刷新表格
function refreshTable(gdh,sec){
    http_get_sync(
        globalVar.URL_SEARCHGDSETPER,
         { 
             gdh: gdh,
             sec: sec
         },
         function(res){
             var tabT = document.getElementById('tabT');
             tabT.innerHTML = "";
             for(var i = 0;i<res.data.length;i++){
                 var personId = res.data[i].id;
                 var personName = res.data[i].name;
                 var time = res.data[i].time;
                 var tr = "<tr><td style='width:14%'><input type='checkbox'></td><td style='width:14%' id='"+personId+"'>" + personId + "</td><td  style='width:14%'>" + personName + "</td><td style='width:22%'>" + gdh + "</td><td style='width:22%'>" + time + "</td><td style='width:14%'><input type='button' class='btn' value='下线'/></td></tr>";
                 $('#tabT').append(tr);
             }
         },
         function(err){
            console.log(err)
            layer.msg("服务端异常,请联系开发人员查看");
        }
    );
}

//选择工艺段
function changeGYD(id){
    var aa = document.getElementById(id);
    var i = aa.selectedIndex;
    var sec = aa.options[i].value;
    document.getElementById(id).value =sec;
    
    var gdh = $('#gdh').val();
    if (id == "gydList") {
       refreshTable(gdh,sec);
    } 
}

//扫码操作
function scanQRCodeClick(id){
    var gdh = $("#gdh").val();
    var gyd = $("#gydList").val();
    var bb = $("#bb").val();
    if (gdh == '') {
        layer.msg("请先输入工单信息!");
        return;
    }
    if (gyd == '请选择工艺段') {
        layer.msg("请先选择工艺段!");
        return;
    }
    if (bb == '请选择') {
        layer.msg("请先选择班别!");
        return;
    }
    
    $(id).attr("disabled", true).css("opacity", 0.3); 
    wx.ready(function() {
    	wx.checkJsApi({ //判断当前客户端版本是否支持指定JS接口
    		jsApiList: ['scanQRCode'],
    		success: function(res) { // 以键值对的形式返回，可用true，不可用false。如：{"checkResult":{"scanQRCode":true},"errMsg":"checkJsApi:ok"}
    			if (res.checkResult.scanQRCode != true) {
    				layer.msg("抱歉，当前客户端版本不支持扫一扫");
    			}
    		},
    		fail: function(res) { //检测getNetworkType该功能失败时处理
    			layer.msg("checkJsApi error");
    		}
    	});
    }); //wx.ready结束
    wx.error(function(res) {
    	layer.msg("错误信息:" + JSON.stringify(res));
    });
    
    wx.scanQRCode({
    	desc: 'scanQRCode desc',
    	needResult: 1,
    	// 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
    	scanType: ["qrCode", "barCode"],
    	// 可以指定扫二维码还是一维码，默认二者都有
    	success: function(res) {
    		console.log("调用扫描成功", res);
    		var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
            $("#codeValue").val(result); //显示结果
            
            http_get( 
                globalVar.URL_SEARCHPERSON,
                {
                    id: result,
                    mo :gdh,
                    sec : gyd,
                },
                function(res){
                    if (res.status) {
                        $("#personName").val(res.data.name); //姓名
                        $("#personState").val(res.data.state); //状态
                    } else {
                    	$("#codeValue").val("");
                    	$("#personName").val(""); //姓名
                    	$("#personState").val(""); //状态
                    	layer.msg(res.message);
                    }
                },
                function(err) {
                    console.log(err)
                    layer.msg("服务端异常,请联系开发人员查看");
                }
            );
        },
        function(err){
            if (err.errMsg.indexOf('function_not_exist') > 0) {
            layer.msg("版本过低请升级");
            }
        }
    });
    $(id).attr("disabled", false).css("opacity", 1); 
}


//上线按钮
function ConfirmUpClick(id){    
 	var personId = document.getElementById('codeValue').value;
 	var personName = document.getElementById('personName').value;
 	var personState = document.getElementById('personState').value;
 	var gdh = document.getElementById('gdh').value;
 	var scxm = document.getElementById('scxm').value;
 	var bb = document.getElementById('bb').value;
 	var sec = document.getElementById('gydList').value;
 	    
    if (bb == '请选择') {
        layer.msg("请先选择班别!");
        return;
    }
    
 	if(bb=='白班'){
 		bb='0';
 	}else if (bb == '晚班'){
 		bb='1';
 	}
    
 	if (personId == '') {
 		layer.msg("请先扫码工卡");
 		return;
 	}
 	if (personName == '') {
 		layer.msg("姓名为空，请等待数据刷新或重新扫码");
 		return;
 	}
    
 	if (personState == '0') {
 		layer.msg("当前员工已处于上线状态");
 		return;
 	}
 	
 	if (sec == '请选择工艺段') {
 		layer.msg("请先选择工艺段!");
 		return;
 	}
 	
 	if (gdh == '') {
 		layer.msg("请先选择工单!");
 		return;
 	}
    $(id).attr("disabled", true).css("opacity", 0.3);
    
    http_get(
        globalVar.URL_CONFIRMUP,
        {
            functionID:globalVar.FUNCTION_ID_UP,
            opid: userId,
            id: personId,
            username:personName,
            bb : bb,
            mo: gdh,
            scxm: scxm,
            sec:sec
        },
        function(res){
            if (res.status) {
                var datetime = res.data.updatetime;
            	var tr = "<tr><td style='width:14%'><input type='checkbox'></td><td style='width:14%' id='ghg'>" + personId + "</td><td style='width:14%'>" + personName + "</td><td style='width:22%'>" + gdh + "</td><td style='width:22%'>" + datetime + "</td><td style='width:14%'><input type='button' class='btn' value='下线'/></td></tr>";
            	$('table').append(tr);
                $("#rptid").val(res.data.rptid);
            	layer.msg(personName + res.data.message);
            } else {
            	layer.msg(res.message);
            }
            $("#codeValue").val("");
            $("#personName").val(""); //姓名		
            $("#personState").val(""); //状态
        },
        function(err){
            console.log(err)
            layer.msg("服务端异常,请联系开发人员查看");
        }
    );
    
    $(id).attr("disabled", false).css("opacity", 1);
}

//列表中 按钮下线
$(function() {
    $("#tab").off('click', '.btn').on("click", "input.btn[value='下线']",
    function(event) {
        event.stopImmediatePropagation(); // 使用更严格的阻止方法
        event.stopPropagation(); // 阻止事件冒泡
        event.preventDefault(); // 阻止默认行为
                        
        var $btn = $(this); // 保存按钮引用
        var gdh = $("#gdh").val();
        var scxm = document.getElementById('scxm').value;
        var bb = document.getElementById('bb').value;
        if(bb=='白班'){
            bb='0';
        }else {
            bb='1';
        } 
        var sec = document.getElementById('gydList').value;
        if (sec == '请选择工艺段') {
            layer.msg("请先选择工艺段!");
            return;
        }
        
        var gh = $btn.closest("tr").find("td").eq(1).text();
        var name = $btn.closest("tr").find("td").eq(2).text();
        var msg = "确认将员工" + gh + "——" + name + "下线？";

        var arr = gh;
        
        $btn.attr("disabled", true).css("opacity", 0.3); 
        
        if (confirm(msg) == true) {
            var i = $(this).closest("tr").index();
            
            //应该优先判断是否需要输入实际产量， 如果需要， 把实际产量输入到下线中完成
             // 创建事件监听方案
            const waitForSjclInput = new Promise((resolve) => {
                window.addEventListener('sjclInputComplete', function handler() {
                    window.removeEventListener('sjclInputComplete', handler);
                    resolve();
                });
                
                pdsjcl(arr, gdh, scxm, sec);
            });
            
            (async() => {
                    // 等待用户完成产量输入
                    await waitForSjclInput;
                    
                    // 用户输入完成后发送请求
                    await new Promise((resolve, reject) => {
                        http_get(
                            globalVar.URL_CONFIRMDOWN,
                            {
                                sjcl: SJCL_QTY, // 使用用户输入后的实际产量值
                                functionID: globalVar.FUNCTION_ID_DOWN,                                
                                opid: userId,
                                id: gh,
                                mo: gdh,
                                sec: sec,
                                scxm :scxm
                            },
                            function(res){
                                resolve(res)
                            },
                            function(err){
                                reject(err)
                            }                            
                        );
                    }).then(function(res){
                        if (res.status) {
                            $('#tab tr').eq(i+1).remove();
                            layer.msg(name + "下线成功");
                        } else {
                            layer.msg(res.message);
                        }
                    }).catch(function(err){
                        console.log(err)
                        layer.msg("服务端异常,请联系开发人员查看");
                    });
                    
            })();
        }  
        
        $btn.attr("disabled", false).css("opacity", 1); 
    });
});


//勾选下线
function ConfirmDownByCheck(){    
    var arr = "";
    var arr1 = new Array();
    var arr2 = new Array();
    var mytable = document.getElementById('tab');
    var rows = document.getElementById('tab').rows;
    var flag = false;
    var sec = $("#gydList").val();
    if(sec=='请选择工艺段'){
    	layer.msg("请先选择工段");
    	return;
    }
    
    for (var i = 0; i < mytable.rows.length; i++) {
    	if(rows[i].cells[0].children[0].checked){
    		flag = true;
    		var id = rows[i].cells[1].innerHTML;
    		var name = rows[i].cells[2].innerHTML;
 
    		arr1.push(name);
            
            if (arr == ""){
                arr = id;
            } else {
                arr = arr + ',' + id;
            }
    	}
    }
    
    if(flag) {
        var gdh = $("#gdh").val();
        var length = arr1.length;
        var msg = "确认将已勾选的"+length+"位员工:"+arr1+"下线?";
        var scxm = document.getElementById('scxm').value;
        var bb = document.getElementById('bb').value;
        if(bb=='白班'){
            bb='0';
        }else{
            bb='1';
        } 
        
        if (confirm(msg) == true) {
            $('#allgltb').attr("disabled", true).css("opacity", 0.3);
            
            //应该优先判断是否需要输入实际产量， 如果需要， 把实际产量输入到下线中完成
            // 创建事件监听方案
            const waitForSjclInput = new Promise((resolve) => {
                // 假设 pdsjcl 完成后会触发 window 上的某个事件
                window.addEventListener('sjclInputComplete', function handler() {
                    window.removeEventListener('sjclInputComplete', handler);
                    resolve();
                });
                
                pdsjcl(arr, gdh, scxm, sec);
            });
            
            
            (async() => {
                    // 等待用户完成产量输入
                    await waitForSjclInput;
                    
                    // 用户输入完成后发送请求
                    await new Promise((resolve, reject) => {
                        http_get(
                            globalVar.URL_DOWNBYCHECK,
                            {
                                sjcl: SJCL_QTY, // 使用用户输入后的实际产量值
                                functionID: globalVar.FUNCTION_ID_DOWN_BYCHECK,   
                                opid : userId,
                                gdh:gdh,
                                ryarr: arr,
                                scxm : scxm,
                                sec : sec,
                            },
                            function(res){
                                resolve(res)
                            },
                            function(err){
                                reject(err)
                            }       
                        );
                    }).then(function(res){
                        if (res.status) {
                            refreshTable(gdh,sec);
                            layer.msg(res.message);
                        }else{
                            layer.msg(res.message);
                        }
                    }).catch(function(err){
                        console.log(err)
                        layer.msg("服务端异常,请联系开发人员查看");
                    });             
            })();
                                      
            $('#allgltb').attr("disabled", false).css("opacity", 1);
    	} 
    }else{
    	layer.msg("未勾选记录");
    }
}

//工单整体下线按钮
function ConfirmDownByGD(id){    
    var gdh = $("#gdh").val();
    var sec = document.getElementById('gydList').value;
    var scxm = document.getElementById('scxm').value;
    var bb = document.getElementById('bb').value;
    if(bb=='白班'){
        bb='0';
    }else{
        bb='1';
    } 
    if (gdh == '') {
        layer.msg("请先输入工单信息!");
        return;
    }
    if (bb == '请选择') {
        layer.msg("请先选择班别!");
        return;
    }
    if (sec == '请选择工艺段') {
        layer.msg("请先选择工艺段!");
        return;
    }
    var mytable = document.getElementById('tab');
    var rows = document.getElementById('tab').rows;
    
    var arr = "";
    if(mytable.rows.length==1){
        layer.msg("请先选择工段，确认该工单-工段下需下线的员工数量!或者该工单-工段下没有员工");
        return;
    } else {
        
        for (var i = 0; i < mytable.rows.length; i++) {
            var id = rows[i].cells[1].innerHTML;
            // arr.push(id);
            if (arr == ""){
                arr = id;
            } else {
                arr = arr + ','+ id;
            }
        }
        
    }
    var msg = "确认将工单:" + gdh +  ",工段:"+sec+"上的员工整体下线？";
    
    $(id).attr("disabled", true).css("opacity", 0.3); 
        
    if (confirm(msg) == true) {
        
        //应该优先判断是否需要输入实际产量， 如果需要， 把实际产量输入到下线中完成
        // 创建事件监听方案
        const waitForSjclInput = new Promise((resolve) => {
            window.addEventListener('sjclInputComplete', function handler() {
                window.removeEventListener('sjclInputComplete', handler);
                resolve();
            });
            pdsjcl(arr,gdh,scxm,sec);
        });
        
        
        (async() => {
            // 等待用户完成产量输入
            await waitForSjclInput;
            
            // 用户输入完成后发送请求
            await new Promise((resolve, reject) => {
                http_get(
                    globalVar.URL_DOWNBYGD,
                    {
                        sjcl: SJCL_QTY, // 使用用户输入后的实际产量值
                        functionID: globalVar.FUNCTION_ID_DOWN_GD,  
                        opid: userId,
                        gdh: gdh,
                        sec:sec ,
                        scxm:scxm,
                        bb:bb 
                    },
                    function(res){
                        resolve(res)
                    },
                    function(err){
                        reject(err)
                    }       
                );
            }).then(function(res){
                if (res.status) {
                    var tabT = document.getElementById('tabT');
                    tabT.innerHTML = "";
                    layer.msg(res.message);
                }else{
                    layer.msg(res.message);
                }
            }).catch(function(err){
                console.log(err)
                layer.msg("服务端异常,请联系开发人员查看");
            });
                               
        })();
        
    }
    
    $(id).attr("disabled", false).css("opacity", 1);
}

//切换工单
function qhgdClick(){
    var value = document.getElementById("qh").style.display;
    if(value=="none"){
      document.getElementById("qh").style.display="block";  
      document.getElementById("gdxxyc2").innerHTML ="收起";  
      document.getElementById('gdxx2').style.display = "block";   
    }else{
      document.getElementById("qh").style.display="none";
      document.getElementById("gdxxyc2").innerHTML ="展开";   
           
      $("#gdh2").val(""); //生产线码
      $("#scxm2").val(""); //生产线码
      $("#cpbm2").val(""); //产品编码
      $("#gdsl2").val(""); //工单数量
      $("#cpms2").val(""); //产品描述
      $("#gdList2").html("");
      $("#gdList2").append("<option>---请选择目标工单---</option>"); 
      $("#gydList2").html("");
      $("#gydList2").append("<option>请选择工艺段</option>"); 
    }
    
    var mytable = document.getElementById('tab');
    // var rows = document.getElementById('tab').rows;
    for (var i = 0; i < mytable.rows.length; i++) {
        if (i != 0 ){
            mytable.rows[i].cells[0].children[0].checked = value==="none";
        }
    }  
}

//取消切换工单
function qhgdCancelClick(){
    document.getElementById("qh").style.display="none";
    $("#gdh2").val(""); //生产线码
    $("#scxm2").val(""); //生产线码
    $("#cpbm2").val(""); //产品编码
    $("#gdsl2").val(""); //工单数量
    $("#cpms2").val(""); //产品描述
    $("#gdList2").html("");
    $("#gdList2").append("<option>---请选择目标工单---</option>"); 
    $("#gydList2").html("");
    $("#gydList2").append("<option>请选择工艺段</option>"); 
}
				
			
            
//确认切换工单
function confirmDownByQHClick() {    
 	var gdh = $("#gdh").val();
 	var gdh2 = $("#gdh2").val();
 	var gydList = $("#gydList").val();
 	var gydList2 = $("#gydList2").val();
 	var flag = true;
 	var bb = document.getElementById('bb').value;
 	if(bb=='白班'){
 		bb='0';
 	}else{
 		bb='1';
 	}
 	if (gdh == ''){
 		layer.msg("请先输入原始工单信息!");
 		return;
 	}
 	if (gydList == '请选择工艺段'){
 		layer.msg("请先选择原工艺段!");
 		return;
 	}
 	if (gdh2 == ''){
 		layer.msg("请先输入目标工单信息!");
 		return;
 	}
 	if (gydList2 == '请选择工艺段'){
 		layer.msg("请先选择目标工艺段!");
 		return;
 	}
 	if(gdh==gdh2){
 		layer.msg("原工单和目标工单不能相同!");
 		return;
 	}
 	var scxm = $("#scxm").val();
 	var scxm2 = $("#scxm2").val();
 	var cpbm2 = $("#cpbm2").val();
 	var gdsl2 = $("#gdsl2").val();
 	var cpms2 = $("#cpms2").val();
 	if(scxm2==''&&cpbm2==''&&gdsl2==''&&cpms2==''){
 		layer.msg("请在输入完目标工单号后,点击查找按钮确认工单信息!");
 		return;
 	}
 	
    var mytable = document.getElementById('tab');
    var rows = document.getElementById('tab').rows;
    var arr = "";
    if(mytable.rows.length==1){
        layer.msg("请先选择工段，确认该工单-工段下需下线的员工数量!或者该工单-工段下没有员工");
        return;
    } else {
        
       
       for (var i = 0; i < mytable.rows.length; i++) {
       	if(rows[i].cells[0].children[0].checked){

       		var id = rows[i].cells[1].innerHTML;
            if (arr == ""){
               arr = id;
            } else {
               arr = arr + ',' + id;
            }
       	}
       }
        
    }
    
 	var msg = "确认将工单:" + gdh +",工艺段:"+gydList+"上的勾选员工转到工单:"+gdh2+",工艺段:" +gydList2+ "上?";
 	
 	$('#qrqh').attr("disabled", true).css("opacity", 0.3);
        
 	if (confirm(msg) == true) {
        // 创建事件监听方案
        const waitForSjclInput = new Promise((resolve) => {
            window.addEventListener('sjclInputComplete', function handler() {
                window.removeEventListener('sjclInputComplete', handler);
                resolve();
            });
            pdsjcl(arr,gdh,scxm,gydList);
        });
        
        
        (async() => {
            // 等待用户完成产量输入
            await waitForSjclInput;
            
            // 用户输入完成后发送请求
            await new Promise((resolve, reject) => {
                http_get(
                    globalVar.URL_QHGD,
                    {
                        sjcl: SJCL_QTY, // 使用用户输入后的实际产量值
                        functionID: globalVar.FUNCTION_ID_QH,  
                        opid: userId,
                        gdh: gdh,
                        gdh2: gdh2,
                        scxm: scxm,
                        scxm2:scxm2,
                        sec:gydList,
                        sec2:gydList2,
                        bb:bb,
                        ryarr:arr
                    },
                    function(res){
                        resolve(res);
                    },
                    function(err){
                        reject(err);
                    }
                );
            }).then(function(res){
                if(res.status){
                    $("#gdh").val(gdh2);
                    suggestGD("gdh");
                    searchClick("search1");
                    $("#gydList").val(gydList2);                    
                    refreshTable(gdh2,gydList2);
                    
                    qhgdCancelClick();
                    layer.msg(res.message);
                }else {
                    layer.msg(res.message);
                }
            }).catch(function(err){
                console.log(err)
                layer.msg("服务端异常,请联系开发人员查看");
            });
        })();
        
 	}
    
    $('#qrqh').attr("disabled", false).css("opacity", 1);
}

//弹框输入产量
function dianwo(gdh,scxm,bb,sec){
    document.getElementById('zhezhao').style.display="";
    $("#gdh_").val(gdh);
    $("#scxm_").val(scxm);
    $("#bb_").val(bb);
    $("#gydList_").val(sec);
}

//报工结束输入实际产量 确认
function sjclok(){
    var sjcl = document.getElementById("sjcl").value;
    if(sjcl==''){
        layer.msg("请先输入实际产量!");
        return;
    }else{
        if(sjcl<=0){
            layer.msg("实际产量必须大于0!");
            return;
        }
    } 
    
    SJCL_QTY = sjcl;
    $("#sjcl").val("");
    document.getElementById('zhezhao').style.display="none";
    // 这里需要添加事件触发
    window.dispatchEvent(new CustomEvent('sjclInputComplete'));
}

//判断实际产量
function pdsjcl(arr,gdh,scxm,sec){        
    SJCL_QTY = 0; //实际产量恢复
    http_get(
        globalVar.URL_PDSJCL,
        {
            ryarr : arr,
            gdh: gdh,
            scxm: scxm,
            sec: sec
        },
        function(res){
            if (res.status) {
                if (res.data.isShow == "Y") {
                    var bb = res.data.bb;
                    dianwo(gdh,scxm,bb,sec);
                } else {
                    // 这里需要添加事件触发
                    window.dispatchEvent(new CustomEvent('sjclInputComplete'));
                }
            } else {
                layer.msg(res.message);
            }
        },
        function(err){
            console.log(err)
            layer.msg("服务端异常,请联系开发人员查看");
        }
    );
}
